<?php
/**
 * Date: 2018/2/5
 * Time: 11:31
 * Author: zeronlee
 */

namespace App\Models\User;


use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class UserAddress extends Model
{

    use softDeletes;

    protected $table = 'user_address';

    protected $primaryKey = 'id';

    public $timestamps = true;

    protected $guarded = [];

    protected $fillable = ['user_id','user_name','province','city','area','street','phone','zip_code','is_default'];

    protected $dates = ['delete_at'];

    /**
     * 插入记录
     * @param mixed $request
     * @return bool
     * @throws \Exception
     */
    public function insertRow($request){
        $data = $request->input();
        //防止越权操作
        try{

            $data['user_id'] = $this->getUserId();
            //刷新默认设置
            $is_default = isset($data['is_default']) ? $data['is_default'] : 0;
            //默认地址刷新
            if ($is_default > 0){
                //可以考虑数据库事务
                $this->flush();
            }
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }

        if ($this->create($data)) {

            return true;
        }

        throw new \Exception('添加失败');

    }
    /**
     * 修改记录
     * @param mixed $request
     * @return bool
     * @throws \Exception
     */
    public function updateRow($request){

        $update = $this->find($request->id);
        //防止越权操作
        try{
            $userId = $this->getUserId();
        } catch (\Exception $e){
            throw new \Exception($e->getMessage());
        }
        if ($update->user_id != $userId) {
            throw new \Exception('非法操作他人收货地址');
        }
        //刷新默认地址
        $data = $request->input();
        $is_default = isset($data['is_default']) ? $data['is_default'] : 0;
        if ($is_default > 0) {
            $this->flush($request->id);
        }
        if($update->update($data)){

            return true;
        }
        throw new \Exception('更新失败');
    }
    /**
     * 删除记录
     * @param mixed $request
     * @return bool
     * @throws \Exception
     */
    public function deleteRow($request){

        $del = $this->find($request->id);
        try {

            $userId = $this->getUserId();
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
        if ( is_null($del) || $del->user_id != $userId) {
            //用户只能操作自己的 避免非法操作删除其他数据
            throw new \Exception('非法删除他人收货地址');
        }
        $del->delete();
        if ($del->trashed()) {
            return true;
        }else{

            throw new \Exception('删除失败');
        }

    }
    /**
     * 某用户收货地址
     * @param mixed $request
     * @return mixed
     * @throws \Exception
     */
    public function getAll($request){

        $where = ['user_id'=>$request->id];

        $address = $this->where($where)->orderBy('created_at','desc')->get();

        if(!$address->isEmpty()){

            return $address;
        }

        throw new \Exception('暂无信息');
    }
    /**
     * 查询单条
     * @param mixed $request
     * @return mixed
     * @throws \Exception
     */
    public function getRow($request){

        if ($request->id){
            $where = ['id'=>$request->id,'user_id'=>$request->user_id];
            $field = ['id','user_name','province','city','area','street','phone','zip_code'];
            return $this->select($field)->where($where)->first();
        }

        throw new \Exception('无效的id');
    }
    /**
     * 设置默认地址 默认地址只能有一条
     * @param int $id = 0
     *
     * @throws \Exception
     */
    protected function flush ($id = 0) {
        //防止越权操作
        try{

            $userId = $this->getUserId();
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
        if ($id !== 0) {
            //修改的情况
            $address = $this->find($id);
            //其他的设置为非默认
            $this->where(['user_id'=>$userId])->where('id','!=',$address->id)->update(['is_default'=>0]);

        } else {
            //增加的情况
            //如果当前数据项包含is_default=1进行操作 否则，不进入该操作
            $this->where(['user_id'=>$userId])->update(['is_default'=>0]);
        }
    }
    /**
     * 获取用户ID debug模式返回0
     * @return int
     * @throws \Exception
     */
    public function getUserId () {
        if (env('APP_DEBUG')) {

            return 0;
        } else {

            if (is_null(\Auth::user())){
                throw new \Exception('用户中心接口越权进入');
            }
            return \Auth::user()->id;
        }
    }
}